package com.zx.www.volunteersystem.controller;

import com.zx.www.volunteersystem.pojo.Notice;
import com.zx.www.volunteersystem.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/notices")


@CrossOrigin(origins = "*")
public class NoticeController {

    //http://localhost:8181/api/notices

    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 发布新公告
     */
    @PostMapping
    public Result publishNotice(@RequestBody Notice notice) {
        try {
            // 设置发布时间为当前时间
            notice.setPublishTime(LocalDateTime.now());
            // 默认不置顶
            if (notice.getIsTop() == null) {
                notice.setIsTop(0);
            }

            int result = noticeMapper.insertNotice(notice);
            if (result > 0) {
                return Result.success("公告发布成功");
            } else {
                return Result.error("公告发布失败");
            }
        } catch (Exception e) {
            return Result.error("公告发布异常: " + e.getMessage());
        }
    }

    /**
     * 获取所有公告（按时间倒序）
     */
    @GetMapping
    public Result<List<Notice>> getAllNotices() {
        try {
            List<Notice> notices = noticeMapper.selectAllNotices();
            return Result.success(notices);
        } catch (Exception e) {
            return Result.error("获取公告列表异常: " + e.getMessage());
        }
    }

    /**
     * 获取置顶公告
     */
    @GetMapping("/top")
    public Result<List<Notice>> getTopNotices() {
        try {
            List<Notice> notices = noticeMapper.selectTopNotices();
            return Result.success(notices);
        } catch (Exception e) {
            return Result.error("获取置顶公告异常: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取公告详情
     */
    @GetMapping("/{id}")
    public Result<Notice> getNoticeById(@PathVariable("id") Integer noticeId) {
        try {
            Notice notice = noticeMapper.selectNoticeById(noticeId);
            if (notice != null) {
                return Result.success(notice);
            } else {
                return Result.error("公告不存在");
            }
        } catch (Exception e) {
            return Result.error("获取公告详情异常: " + e.getMessage());
        }
    }

    /**
     * 更新公告
     */
    @PutMapping("/{id}")
    public Result updateNotice(@PathVariable("id") Integer noticeId, @RequestBody Notice notice) {
        try {
            System.out.println("开始更新公告，ID: " + noticeId);
            System.out.println("接收到的数据: " + notice);

            // 获取原始公告信息
            Notice originalNotice = noticeMapper.selectNoticeById(noticeId);
            if (originalNotice == null) {
                return Result.error("公告不存在");
            }

            // 设置更新信息
            notice.setNoticeId(noticeId);
            // 保留原始的发布时间
            notice.setPublishTime(originalNotice.getPublishTime());
            // 确保其他必要字段不为空
            if (notice.getIsTop() == null) {
                notice.setIsTop(0);
            }

            System.out.println("更新前的完整数据: " + notice);

            int result = noticeMapper.updateNotice(notice);
            if (result > 0) {
                return Result.success("公告更新成功");
            } else {
                return Result.error("公告更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公告更新异常: " + e.getMessage());
        }
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/{id}")
    public Result deleteNotice(@PathVariable("id") Integer noticeId) {
        try {
            int result = noticeMapper.deleteNotice(noticeId);
            if (result > 0) {
                return Result.success("公告删除成功");
            } else {
                return Result.error("公告删除失败");
            }
        } catch (Exception e) {
            return Result.error("公告删除异常: " + e.getMessage());
        }
    }

    /**
     * 根据发布人ID获取公告
     */
    @GetMapping("/publisher/{publisherId}")
    public Result<List<Notice>> getNoticesByPublisher(@PathVariable("publisherId") Integer publisherId) {
        try {
            List<Notice> notices = noticeMapper.selectNoticesByPublisherId(publisherId);
            return Result.success(notices);
        } catch (Exception e) {
            return Result.error("获取发布人公告异常: " + e.getMessage());
        }
    }
}

// 统一返回结果类
class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.code = 200;
        result.message = "操作成功";
        result.data = data;
        return result;
    }

    public static <T> Result<T> error(String message) {
        Result<T> result = new Result<>();
        result.code = 500;
        result.message = message;
        return result;
    }

    // Getters and Setters
    public Integer getCode() { return code; }
    public void setCode(Integer code) { this.code = code; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
    public T getData() { return data; }
    public void setData(T data) { this.data = data; }
}
